import 'package:flutter/material.dart';

import 'package:flutter_cashier/flutter_cashier.dart';
import 'package:flutter_cashier/eventbus.dart';

import 'http.dart';

void main() {
  runApp(const MaterialApp(home: DemoApp()));
}

class DemoApp extends StatefulWidget {
  const DemoApp({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() {
    return _PayResPage();
  }
}

class _PayResPage extends State<StatefulWidget> {
  //订单参数
  static const orderInfo = {
    'orderNo': '12346',
    'orderAmt': '12.22',
  };
  //支付宝模拟支付参数
  static const AliPayExam = 'alipay_sdk=alipay-sdk-java-dynamicVersionNo&app_id=2021001161665061&biz_content=%7B%22out_trade_no%22%3A%22LS1693088431%22%2C%22passback_params%22%3A%22platformType%253DAPP%22%2C%22product_code%22%3A%22QUICK_MSECURITY_PAY%22%2C%22subject%22%3A%22%E9%9C%80%E6%96%B9APP%E6%94%AF%E4%BB%98%E8%AE%A2%E5%8D%95%22%2C%22timeout_express%22%3A%2230m%22%2C%22total_amount%22%3A%220.01%22%7D&charset=UTF-8&format=json&method=alipay.trade.app.pay&notify_url=https%3A%2F%2Fuat-gateway.vandream.com%2Fcapp%2Falipay%2Fnotify&sign=Yu4Dmxlb7QPx5etceB%2F%2BMODziA%2BPzZTZwUwx7lmzRskWSaKqF7ESik6Ls3WXWEL9niyD%2BERGyFQia75f90BKLWfo%2Ba6yAobJ8IxZuPQgeCx0YSq32TkfZDRav437h0ceZ%2Faqm9kG7a3Z71PK%2BKm6ehUFu49jMbr7rhPGvvPAi8tKsMPp9fe29rkJd%2FpACHdThtEOrOeyIo6AW01jVIdB0tdu9DeSsrqtGwb0rzXpXUc4u%2FkAW2qfcKhtR8GkOR1WeUYYG0MH20sLbFM%2FzJsYCLEQyg0pEgix3mx5JD3VZFXBCRvcum59ndS0TrJtgdMZht774pwRQdLboLm3z482Bg%3D%3D&sign_type=RSA2&timestamp=2021-11-17+19%3A57%3A23&version=1.0';
  //微信小程序模拟参数
  static const WeixinMPExam = {
    'appId': 'wxe1351e86a7da566d',
    'path': 'pages/index/index',
    'orderNo': '12346',
    'orderAmt': '12.22',
    'userName': 'gh_b4cd5326de17',
    'mpEnv': '2',
  };
  //微信APP支付模拟参数
  static const WeixinExam = {
    "package": "Sign=WXPay",
    "appid": "wxe1351e86a7da566d",
    "sign": "FAAC6166A519C7152922EB8065758111",
    "partnerid": "1584940631",
    "prepayid": "wx17195541383725b884986e423a21460000",
    "noncestr": "1637150140855",
    "timestamp": '1637150140'
  };
  Map? payRes;

  @override
  void initState() {
    super.initState();
    //收银台支付方式选择后获取对应的支付单信息，再发送给收银台
    bus.on("payMethodChange", (payMethod) async {
      Object? param;
      if(payMethod == 'WeiXin'){
        param  = WeixinExam;
      }else if(payMethod == 'AliPay'){
        param  = await aliPayParam();
      }
      //再发送给收银台
      bus.emit('setPayData',param);

    });
  }

  Future<String> aliPayParam() async{
    var data = await Http.request(Http.Url);
    print('支付宝支付\n'+Uri.decodeComponent(data));
    return data;
  }

  @override
  void dispose() {
    super.dispose();
    //移除事件观察者
    bus.off('payMethodChange');
  }


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter Cashier Demo'),
      ),
      body: Container(
        padding: const EdgeInsets.all(18),
        child: Column(
          children: [
            Align(
                alignment: Alignment.centerLeft,
                child: Text("订单参数:\n$orderInfo")),
            const SizedBox(height: 50),
            Align(
                alignment: Alignment.centerLeft,
                child: Text("支付结果:\n$payRes")),
            const SizedBox(height: 50),
            Row(children: [
              Expanded(
                child: MaterialButton(
                    child: const Text('Open Cashier'),
                    textTheme: ButtonTextTheme.primary,
                    color: Colors.green,
                    splashColor: Colors.blue,
                    elevation: 10.0,
                    height: 44,
                    highlightElevation: 20.0,
                    padding: const EdgeInsets.only(left: 20, right: 20),
                    onPressed: () => {
                      Navigator.push(context,
                          MaterialPageRoute(builder: (context) {
                            return const FlutterCashier(orderInfo: orderInfo);
                          })).then((res) => {
                        //支付完成回调
                        if(res != null){
                          setState(() {
                            res['result'] = '';
                            payRes = res;
                          })
                        }
                      })
                    }),
              ),
            ],)
          ],
        ),
      ),
    );
  }
}
